package agentd_mux1

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var ListenAddr = "127.0.0.1:12680"

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

type Server struct {
	Proxy *TProxy
}

var DefaultServer *Server

func NewServer() *Server {
	urlPrefix := "/partner-service"

	proxy, _ := NewProxy(Config{
		Upgrader:  upgrader,
		URLPrefix: urlPrefix,
	})

	return &Server{
		Proxy: proxy,
	}
}

func HandleEcho(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)

	if err != nil {
		log.Printf("failed to upgrade: %v", err)
		return
	}

	for {

		msgType, msg, err := conn.ReadMessage()
		if err != nil {
			return
		}

		fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))

		if err = conn.WriteMessage(msgType, msg); err != nil {
			return
		}
	}
}

// func HandlePartnerService(w http.ResponseWriter, r *http.Request) {
// 	http.ServeFile(w, r, "index.html")
// }

func HandleIndex(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "index.html")
}

func (s *Server) Start() {
	http.Handle("/partner-service/", s.Proxy)

	http.HandleFunc("/echo", HandleEcho)

	http.HandleFunc("/", HandleIndex)

	log.Printf("Listening on %s...", ListenAddr)
	log.Fatal(http.ListenAndServe(ListenAddr, nil))
}
